/* 
 * @name login.js
 * @author : Amissah Gideon<kuulmek@yahoo.com>
 * @version 1.0
 */
 
var login = {
		/* Server script url   */
		ssUrl : null,

		/* Function init
		 * This function is the constructor of the Object login.
		 * It initialises certain DOM ids of the login screen and listens to the user actions to perform.
		 * @param void
		 * @return void
		 * @access public
		 * */
		init:function(){
			/* When the page is loaded set the focus on the username field */
			$('#username').focus();
			$("#login-form").validationEngine();
			/* Execute all user's actions on the page */
			//submit the form;
			$('#login').click(function(){
				login.submitForm();
				return false;
			});
		},


		/* Function to submit the login form
		 *This function submits the form after some validations are done.
		 *@name submitForm
		 *@return void
		 *@access public
		 **/
		submitForm:function(){
			/* Validation Status of the Login Form. It checks whether the data input by the user are correct or not. */
			var validationStatus = $('#login-form').validationEngine({returnIsValid:true});

			/* When the Validation Status is true meaning that the data input are correct then the data can be processed. */
			if(validationStatus){
				/* Preparation of the data to send to the server to be processed. Here we retrieve the data from the login form. */
				var query = $('#login-form').serialize();
				login.ssUrl = $('#login-url').attr('data-url');
				/* Send the data to the server and handle the server response */
				$.post(login.ssUrl, query, function(response){
					 var txt = '';
						
						if(typeof response.mesg  == 'object'){
							for(megTxt in response.mesg){
								txt += response.mesg[megTxt]+'<br />';
							}
						}
						else{
							txt = response.mesg
						}  
					/* When everything went on smoothly on the server redirect the user to the appropriate page.*/
					if(response.code === 0){
						$.validationEngine.buildPrompt(".login-prompt","Login Success!!! Redirecting...","pass");
						window.location = 'Users/signIn';
					}
					/* When there are Errors */
					else if(response.code === 1){
						$.validationEngine.buildPrompt(".login-prompt",txt,"error");
					}
				},'json');
			}
		}
};

/* when the page is loaded */
$(document).ready(function() {
	login.init();
});